package com.fuyao.cloud.daemon.quartz.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fuyao.cloud.common.core.constant.SecurityConstants;
import com.fuyao.cloud.constant.MessageUserobjectConstant;
import com.fuyao.cloud.message.dto.ManagementUserObjectSearchDTO;
import com.fuyao.cloud.message.entity.ShoreMessageRecord;
import com.fuyao.cloud.message.entity.SystemMessageRecord;
import com.fuyao.cloud.message.feign.RemoteMessageService;
import com.fuyao.cloud.message.util.IpUtil;
import com.fuyao.cloud.message.util.MacUtil;
import com.fuyao.cloud.message.vo.ManagementUserObjectVO;
import com.fuyao.cloud.message.vo.MesRuleFormVO;
import com.fuyao.cloud.message.vo.MessageRuleVO;
import com.fuyao.cloud.sms.api.SmsDTO;
import com.fuyao.cloud.sms.api.feign.RemoteSmsService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lyhil
 */
@Slf4j
public class MessageUtil {
    private static MsgRuleDispose msgRuleDispose;
    private final static String TERM = "0";
    /**
     * 短信
     */
    private final static String MODE_0 = "0";
    /**
     * 系统消息
     */
    private final static String MODE_1 = "1";
    /**
     * 电子邮箱
     */
    private final static String MODE_2 = "2";

    private final static String MODE_0_CN = "短信";
    private final static String MODE_1_CN = "系统消息";
    private final static String MODE_2_CN = "邮件";

    public static void sendShoreMessage(RemoteMessageService messageService, String param, RemoteSmsService remoteSmsService) {
        List<ShoreMessageRecord> messageRecordList = Lists.newArrayList();
        ManagementUserObjectSearchDTO searchDTO = new ManagementUserObjectSearchDTO();
        searchDTO.setMode(MODE_0);
        searchDTO.setJobName(param);
        List<ManagementUserObjectVO> resultList = messageService.listManagementUserObjectMode(searchDTO, SecurityConstants.FROM_IN).getData();
        if (CollUtil.isNotEmpty(resultList)) {
            resultList.forEach(r -> {
                if (judgeDateScope(r)) {
                    messageRecordList.add(addSendShortMessage(r));
                }
            });

            List<SmsDTO> smsDTOList = messageRecordList.stream().filter(msg -> StrUtil.isNotEmpty(msg.getPhone())).map(msg -> {
                SmsDTO smsDTO = new SmsDTO();
                smsDTO.setMobile(msg.getPhone());
                smsDTO.setContent(msg.getSendContent());
                return smsDTO;
            }).collect(Collectors.toList());
            // 调用短信发送接口。
            remoteSmsService.sendSmsList(smsDTOList, SecurityConstants.FROM_IN);

            log.info("短信发送记录：{}", resultList.size());
            // 保存短信发送记录
            messageService.saveShoreMessageList(messageRecordList, SecurityConstants.FROM_IN);
        }
    }

    public static void sendSystemMessage(RemoteMessageService messageService, String param) {
        ManagementUserObjectSearchDTO searchDTO = new ManagementUserObjectSearchDTO();
        searchDTO.setMode(MODE_1);
        searchDTO.setJobName(param);
        List<SystemMessageRecord> systemMessageRecordList = Lists.newArrayList();
        List<ManagementUserObjectVO> resultList = messageService.listManagementUserObjectMode(searchDTO, SecurityConstants.FROM_IN).getData();
        if (CollUtil.isNotEmpty(resultList)) {
            resultList.forEach(r -> {
                if (judgeDateScope(r)) {
                    systemMessageRecordList.add(addSendSystemMessage(r));
                }
            });
            log.info("系统消息发送条数：{}", resultList.size());
            // 保存短信发送记录
            messageService.saveSystemMessageList(systemMessageRecordList, SecurityConstants.FROM_IN);
        }

        // 规则
        List<ManagementUserObjectVO> messageManagements = messageService.listManagement(searchDTO, SecurityConstants.FROM_IN).getData();
        if (CollUtil.isNotEmpty(messageManagements)) {
            // 是否建立规则
            for (int i = 0; i < messageManagements.size(); i++) {
                ManagementUserObjectVO m = messageManagements.get(i);
                if (judgeDateScope(m.getTimelimitType(), m.getStartdate(), m.getEnddate())) {
                    List<MessageRuleVO> ruleVOS = messageService.listMessageRules(m.getId(), SecurityConstants.FROM_IN).getData();
                    if (CollUtil.isNotEmpty(ruleVOS)) {
                        List<MesRuleFormVO> mesRuleFormVOS = msgRuleDispose.disposeRules(ruleVOS);
                        if (mesRuleFormVOS.size() > 0) {
                            List<SystemMessageRecord> systemMessageRecords = Lists.newArrayList();
                            for (int j = 0; j < mesRuleFormVOS.size(); j++) {
                                systemMessageRecords.add(addSendSystemMessage(m, mesRuleFormVOS.get(i)));
                            }
                            // 保存短信发送记录
                            messageService.saveSystemMessageList(systemMessageRecords, SecurityConstants.FROM_IN);
                        }
                    }
                }
            }
        }
    }

    /**
     * 判断是否范围
     *
     * @param objectVO 查询发送短信对象
     * @return true false
     */
    private static boolean judgeDateScope(ManagementUserObjectVO objectVO) {
        LocalDate curLocalDate = LocalDate.now();
        // 长期坚持直接返回 true
        if (TERM.equals(objectVO.getTimelimitType())) {
            return Boolean.TRUE;
        }
        return curLocalDate.isAfter(objectVO.getStartdate()) && curLocalDate.isBefore(objectVO.getEnddate());
    }

    private static boolean judgeDateScope(String timelimitType, LocalDate start, LocalDate end) {
        LocalDate curLocalDate = LocalDate.now();
        // 长期坚持直接返回 true
        if (TERM.equals(timelimitType)) {
            return Boolean.TRUE;
        }
        return curLocalDate.isAfter(start) && curLocalDate.isBefore(end);
    }

    /**
     * 添加短信发送记录
     *
     * @param objectVO 短信发送对象
     */
    @SneakyThrows
    private static ShoreMessageRecord addSendShortMessage(ManagementUserObjectVO objectVO) {
        ShoreMessageRecord messageRecord = new ShoreMessageRecord();
        messageRecord.setCreatedId(objectVO.getUserUserid());
        messageRecord.setCreatedBy(objectVO.getUserName());
        messageRecord.setCreatedTime(LocalDateTime.now());
        messageRecord.setTenantId(objectVO.getTenantId());
        messageRecord.setMac(MacUtil.getMacAddress());
        messageRecord.setIp(IpUtil.getHostIp());
        messageRecord.setSendCode("001");
        messageRecord.setSendStatus(0);
        messageRecord.setPhone(objectVO.getPhoneNumber());
        messageRecord.setSendContent(objectVO.getInfor());
        return messageRecord;
    }

    /**
     * 添加短信发送记录
     * datease
     * 1.单点登录
     * 2.更新到最新版本
     * 3.完善权限
     * 4.阻断远程访问
     *
     * @param objectVO 短信发送对象
     */
    @SneakyThrows
    private static SystemMessageRecord addSendSystemMessage(ManagementUserObjectVO objectVO) {
        SystemMessageRecord messageRecord = new SystemMessageRecord();
        messageRecord.setCreatedId(objectVO.getUserUserid());
        messageRecord.setCreatedBy(objectVO.getRealName());
        messageRecord.setCreatedTime(LocalDateTime.now());
        messageRecord.setTenantId(objectVO.getTenantId());
        messageRecord.setContent(objectVO.getInfor());
        messageRecord.setRemarks(objectVO.getRemarks());
        messageRecord.setTypeCode(objectVO.getOpenType());
        if (objectVO.getOpenType().equals(MessageUserobjectConstant.INTERNAL_JUMP)) {
            if (!StrUtil.isEmptyIfStr(objectVO.getOpenUrl())) {
                String path = MsgParamUtil.getPath(objectVO.getOpenUrl(), objectVO.getSourceId());
                messageRecord.setOpenUrl(path);
            }
        } else {
            messageRecord.setOpenUrl(objectVO.getOpenUrl());
        }
        return messageRecord;
    }

    @SneakyThrows
    private static SystemMessageRecord addSendSystemMessage(ManagementUserObjectVO objectVO, MesRuleFormVO m) {
        return addSendSystemMessage(objectVO, m.getUserId(), m.getRealName(), m.getSourceId());
    }

    @SneakyThrows
    private static SystemMessageRecord addSendSystemMessage(ManagementUserObjectVO objectVO, Long userId, String userName, Long sourceId) {
        SystemMessageRecord messageRecord = new SystemMessageRecord();
        messageRecord.setCreatedId(userId);
        messageRecord.setCreatedBy(userName);
        messageRecord.setCreatedTime(LocalDateTime.now());
        messageRecord.setTenantId(objectVO.getTenantId());
        messageRecord.setContent(objectVO.getInfor());
        messageRecord.setRemarks(objectVO.getRemarks());
        messageRecord.setTypeCode(objectVO.getOpenType());
        if (objectVO.getOpenType().equals(MessageUserobjectConstant.INTERNAL_JUMP)) {
            if (!StrUtil.isEmptyIfStr(objectVO.getOpenUrl())) {
                String path = MsgParamUtil.getPath(objectVO.getOpenUrl(), sourceId);
                messageRecord.setOpenUrl(path);
            }
        } else {
            messageRecord.setOpenUrl(objectVO.getOpenUrl());
        }
        return messageRecord;
    }

    /**
     * 根据精英判断发送
     *
     * @param messageService 消息服务
     * @param param          参数 短信|定时任务名称
     */
    public static void sendMessage(RemoteMessageService messageService, String param, RemoteSmsService remoteSmsService, MsgRuleDispose ruleDispose) {
        String paramStr = param.substring(param.indexOf("-") + 1);
        msgRuleDispose = ruleDispose;
        if (param.contains(MODE_0_CN)) {
            sendShoreMessage(messageService, paramStr, remoteSmsService);
        }
        if (param.contains(MODE_1_CN)) {
            sendSystemMessage(messageService, paramStr);
        }
    }
}
